package it.polimi.sartori_daniello_picca.meteocal.boundary;

import it.polimi.sartori_daniello_picca.meteocal.entity.Calendar;
import it.polimi.sartori_daniello_picca.meteocal.entity.Contains;
import it.polimi.sartori_daniello_picca.meteocal.entity.Event;
import it.polimi.sartori_daniello_picca.meteocal.entity.Users;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author Ale
 */
@Stateless
public class EventManager {
    
    @PersistenceContext
    private EntityManager em;
    
    public void create(Event event, String username) {
        Users loggeduser = em.find(Users.class, username);
        event.setCreator(loggeduser);
        em.persist(event);
    }
    
    public void edit(Event entity) {
        em.merge(entity);
    }
    
    public void delete(Event entity) {
        em.remove(entity);
    }
    
    public Event findevent(int id) {
        return em.find(Event.class, id);
    }
    
    public List<Calendar> findParticipants(Event e){
        return em.createNamedQuery(Contains.findByEvent, Calendar.class)
                .setParameter("event", e)
                .getResultList();
    }
    
    public List<Event> searchingPublicEvent (String eventname, String place, Date dataEvento){
        
          if(eventname == null){
              eventname = "";
          }
          if(dataEvento == null){
              dataEvento = new Date();
          }
          if(place == null){
              place = "";
          }
           List<Event> result = em.createNamedQuery(Event.advancedSearch, Event.class)
                  .setParameter("eventname", "%"+eventname+"%")
                  .setParameter("place", "%"+place+"%")
                  .setParameter("dataevento", dataEvento)
                  .getResultList();
          
          return result;
          }

     public List<Event> searchByCreator (String eventname, Users creator) {
         List<Event> result = em.createNamedQuery(Event.findByCreator, Event.class)
                  .setParameter("eventname", "%"+eventname+"%")
                  .setParameter("creator", creator)
                  .getResultList();
    return result;
    }
}